#include "index.hpp"
#include "util.hpp"
#include <string>
#include <vector>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include "log.hpp"

namespace ns_searcher {

    struct InvertedElemPrint {
        uint64_t doc_id;
        int weight;
        std::vector<std::string> words;
        InvertedElemPrint() :doc_id(0), weight(0) {}
    };


    class Searcher {
    private:
        ns_index::Index *index;  // 供系统进行查找的索引
    public:
        Searcher() {}
        ~Searcher() {}
    public:
        void InitSearcher(const std::string &input)
        {
            // 1. 获取或者创建index对象
            index = ns_index::Index::GetInstance();
            // std::cout << "获取单例对象成功......" << std::endl;
            LOG(Info, "获取单例对象成功");
            
            // 2. 根据index对象建立索引
            index->BuildIndex(input); 
            // std::cout << "index对象建立索引成功" << std::endl;
            LOG(Info, "建立正排和倒排索引成功");

        }

        // query: 搜索关键字    json_string: 返回给用户浏览器的搜索结果
        void Search(const std::string &query, std::string *json_string)
        {
            // 1. [分词]: 对query进行按照searcher的要求进行分词
            std::vector<std::string> words;
            ns_util::JiebaUtil::CutString(query, &words);
            
            // 2. [触发]: 根据分词的各个"词",进行index查找
            std::vector<InvertedElemPrint> inverted_list_all;
            std::unordered_map<uint64_t, InvertedElemPrint> tokens_map;

            for (std::string word : words) {
                boost::to_lower(word);
                ns_index::InvertedList *inverted_list = index->GetInvertedList(word);
                if (nullptr == inverted_list) {
                    continue;
                }

                for (const auto &elem : *inverted_list) {
                    auto &item = tokens_map[elem.doc_id];
                    item.doc_id = elem.doc_id;
                    item.weight += elem.weight;
                    item.words.push_back(elem.word);
                }
            }
            for (const auto &item : tokens_map) {
                inverted_list_all.push_back(std::move(item.second));
            }
            // 3. [合并排序]: 汇总查找结果, 按照相关性(weight)降序排序
            std::sort(inverted_list_all.begin(), inverted_list_all.end(),
            [](const InvertedElemPrint &e1, const InvertedElemPrint &e2){
                return e1.weight > e2.weight;
            });
            // 4. [构建]: 根据查找出来的结果,构建json串 -- jsoncpp
            Json::Value root;
            for (auto &item : inverted_list_all) {
                ns_index::DocInfo *doc = index->GetForwardIndex(item.doc_id);
                if (nullptr == doc) {
                    continue;
                }
                Json::Value elem;
                elem["title"] = doc->title;
                elem["desp"] = GetDesp(doc->content, item.words[0]);  // content是文档去标签后的结果,而这里需要的只是部分,用来描述文档内容的
                elem["url"] = doc->url;
                // debug
                elem["weight"] = item.weight;
                elem["doc_id"] = (int)item.doc_id;
                root.append(elem);
            }

            Json::StyledWriter writer;
            *json_string = writer.write(root);
        }

        std::string GetDesp(const std::string &html_content, const std::string &word)
        {
            // 找到word在html_content中首次出现的位置,然后往前找50字节(如果没有,就从begin开始),往后找80字节(如果没有,到end就行)
            // 截出这部分
            const int prev_step = 50;
            const int next_step = 80;

            // 1. 找到首次出现
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](int x, int y){ 
                return (std::tolower(x) == std::tolower(y));
            });
            if (iter == html_content.end()) {
                LOG(Warning, "GetDesp Error");
                return "None1";
            }
            std::size_t pos = std::distance(html_content.begin(), iter);

            // 2. 获取start, end
            std::size_t start = 0;
            std::size_t end = html_content.size()-1;
            // 如果之前有50+字符,就更新开始位置, 结束位置同理
            if (pos  > start + prev_step) start = pos - prev_step;  // pos - prev_step > start 的写法是错的, 因为pos - prev_step, 类型是size_t, 如果pos < prev_step的话,其结果很大
            if (pos + next_step < end) end = pos + next_step;

            // 3. 截取字符串,
            if (start >= end) {
                LOG(Warning, "GetDesp Error");
                return "None2";
            }
            return html_content.substr(start, end - start) + "......";
        }

    };


}